# -*- coding: utf-8 -*-

###########################################################################
#
#   Copyright (c) 2020  Bresee, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###########################################################################


import time
import utils.pgsql.base.pgconn as pgconn
"""
operater table management
add 
delete
modify
...
"""
_tblName = 'tbl_operator'

_DB_SCRIPT = """
CREATE TABLE IF NOT EXISTS {} (
                "operatorId"  SERIAL PRIMARY KEY ,    
                "operatorName"  VARCHAR(260) NOT NULL default '' unique,    
                "phone"  VARCHAR(260) NOT NULL default '',    
                "account"  VARCHAR(260) NOT NULL default '',    
                "adminId"  INTEGER NOT NULL default 0,    
                "createTime" VARCHAR(32) NOT NULL default '',
                "updateTime" VARCHAR(32) NOT NULL default '',
                "dataValid" INTEGER NOT NULL default 1
                );

""".format(_tblName)


class PgOperator:

    def __init__(self):
        self._pgConn = pgconn.pgMainConn

    def __del__(self):
        pass

    def createTbl(self):
        """
        create
        :return:
        """
        return self._pgConn.exec(_DB_SCRIPT)

     
    def addOperator(self, dic) -> str:
         
        dic['createTime'] = time.strftime(
            "%Y-%m-%d %H:%M:%S", time.localtime())
        sql_key = '\"' + '\", \"'.join(dic.keys()) + '\"'
        sql_val = ''
        for key in dic:
            if type(dic[key]) is str:
                sql_val = sql_val + '\'' + dic[key] + '\','
            else:
                sql_val = sql_val + str(dic[key]) + ' ,'

        
        sql = f"""insert into {_tblName} ({sql_key}) values ({sql_val[:-1]}) RETURNING "{"operatorId"}" """

        return pgconn.pgMainConn.exec_fetchone(sql)

  
    def update_adminId(self, operatorId, adminId) -> list:
        sql = "update {} set \"adminId\" = \'{}\' where \"operatorId\" = \'{}\'".format(
            _tblName, adminId, operatorId)
        return pgconn.pgMainConn.exec(sql)

 
    def all(self) -> list:
        sql = "select * from {} where \"dataValid\" = \'1\' order by \"operatorId\" ".format(_tblName)
        # print(sql)
        return self._pgConn.exec_fetchall(sql)

 
    def get(self, ids) -> dict:
        sql = "select * from {} where \"operatorId\" = \'{}\'".format(
            _tblName, ids)
        return self._pgConn.exec_fetchone(sql)

 
    def getUnusedOperator(self) -> list:
        sql = "select * from {} where \"adminId\" = \'0\' and \"dataValid\" = \'1\' ".format(
            _tblName)
        return self._pgConn.exec_fetchall(sql)

 
    def getoperatornamer(self,ids) -> list:
        sql = "select \"operatorName\" from {} where \"operatorId\" = {} ".format(
            _tblName,ids)
        return self._pgConn.exec_fetchone(sql)
    
 
    def modify(self, dic, key1, ids) -> bool:
        dic['updateTime'] = time.strftime(
            "%Y-%m-%d %H:%M:%S", time.localtime())

        sql_key = ''
        for key in dic:
            if type(dic[key]) is str:
                sql_key = sql_key + '\"' + key + '\"' + ' = \'' + dic[key] + '\','
            else:
                sql_key = sql_key + '\"' + key + '\"' + ' = ' + str(dic[key]) + ' ,'


        sql =  "update {} set {} where  ".format(_tblName, sql_key[:-1]) + " \"{}\" = \'{}\' ".format(key1, ids)
        print(sql)
        return self._pgConn.exec(sql)


 
    def delete(self, ids) -> bool:
        sql = "delete from {} where \"operatorId\" = \'{}\' ".format(
            _tblName, ids)
        return self._pgConn.exec(sql)
    
 
    def soft_delete(self,ids,operatorName) -> bool:
        operatorName = operatorName +  str(int(time.time()))
        sql = "update {} set \"dataValid\" = \'0\' , \"operatorName\" = \'{}\'  where \"operatorId\" =  \'{}\' ".format(_tblName,operatorName, ids)

        return self._pgConn.exec(sql)
